﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace UnitTest
{
    public class 任务超出指定时间停止
    {
        public static void Go()
        {
            Console.Write("dasdsa");
            ts();
            //var res = Test();
            Console.Write("aaaa");

           //string res= TestAsync();
           //Console.Write(res);
        }


        public static string TestAsync()
        {
            var source = new CancellationTokenSource();
            string result = "";
            Task task = new Task(() =>
            {
                while (!source.IsCancellationRequested)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(6));
                    result = "成功！";
                    Console.Write("dasdas");
                    source.Cancel();
                }
            },source.Token);
            source.CancelAfter(2000);
            task.RunSynchronously();
            Console.Write("结束");
            //string ads = task.Result;
            return result;
        }

        public static bool Test()
        {
            string result = "";
            var task = Task.Run(() =>
            {
                Thread.Sleep(TimeSpan.FromSeconds(4));
                result = "成功！";
                Console.Write("dasdas");
            });
            if (task.Wait(TimeSpan.FromSeconds(3)))
                return true;
            else
            return false;
        }

        public static void ts()
        {

            var obj = new object();
            bool lockWasTaken=true;

            try
            {
                lockWasTaken = Monitor.TryEnter(obj, 3000);
                if (lockWasTaken) ;
                {
                    Console.Write("进入");
                    Thread.Sleep(4000);
                    Console.Write("成功");
                }
            }
            finally
            {
                if (lockWasTaken)
                {
                    Monitor.Exit(obj);
                }
            }
        }
    }
}
